package com.silence.whereeat.servlet;

import com.silence.whereeat.dao.FoodInfoDao;
import com.silence.whereeat.model.FoodInfo;
import com.silence.whereeat.service.FoodInfoService;
import com.silence.whereeat.utils.GsonUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 获取食物信息
 * Created by 伟阳 on 2015/9/22.
 */
public class GetFoodInfoServlet extends HttpServlet {

    private FoodInfoService getFoodInfo;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int food_id = Integer.parseInt(request.getParameter("food_id").trim());
        FoodInfo foodInfo = getFoodInfo.getFoodInfoById(food_id);
        PrintWriter out = response.getWriter();
        if (foodInfo != null) {
            String foodInfoJsonString = GsonUtils.createJsonString(foodInfo);
            out.println(foodInfoJsonString);
        } else {
            out.println("null");
        }
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void init() throws ServletException {
        getFoodInfo = new FoodInfoDao();
    }

    @Override
    public void destroy() {
        getFoodInfo.close();
    }
}
